﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Kendo.Mvc.Extensions;
using Kendo.Mvc.UI;
using Microsoft.AspNet.Identity;
using QuickPrompt.DomainModel;
using QuickPromt.Service;

namespace QuickPrompt.Spa.Controllers
{
    public class PromptController : Controller
    {
        private readonly IQuickPromptService _quickPromptService;

        public PromptController(IQuickPromptService quickPromptService)
        {
            _quickPromptService = quickPromptService;
        }

        // GET: Prompt
        [HttpPost]
        public ActionResult Read([DataSourceRequest] DataSourceRequest request, int id)
        {
            List<Prompt> prompts = _quickPromptService.Get(id);
            if (prompts == null)
                return new HttpUnauthorizedResult();
            if (prompts.FirstOrDefault(x => x.QuickNote.UserGuid != User.Identity.GetUserId()) != null)
                return new HttpUnauthorizedResult();

            var filteredProperties = prompts.Select(
                x =>
                    new
                    {
                        x.Id,
                        x.NoteId,
                        x.PromptFrequency,
                        x.PromptType,
                        x.PromptTimeZone,
                        x.IsActive,
                        x.DateCreatedUtc,
                        x.AddressValue,
                        x.StartingFromUtc
                    })
                .ToList();

            return Json(filteredProperties.ToDataSourceResult(request));
        }

        [HttpPost]
        public ActionResult Create([DataSourceRequest] DataSourceRequest request, Prompt prompt, int parentId)
        {
            prompt.NoteId = parentId;
            _quickPromptService.Insert(prompt);
            _quickPromptService.SaveChanges();
            return Json(true);
        }

        [HttpPost]
        public ActionResult Update([DataSourceRequest] DataSourceRequest request, Prompt prompt)
        {
            _quickPromptService.Update(prompt);
            _quickPromptService.SaveChangesAsync();
            return Json(true);
        }

        [HttpPost]
        public ActionResult Destroy([DataSourceRequest] DataSourceRequest request, int id)
        {
            _quickPromptService.SetToDelete(id);
            _quickPromptService.SaveChangesAsync();
            return Json(true);
        }
    }
}